home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 9A / PC Extra 9A-2000.iso / utveckla / perl / gb.cgi next >
Encoding:
Text File  |  2000-07-21  |  6.9 KB  |  209 lines

  1. #!/usr/bin/perl
  2.  
  3. #------------------- standard CGI skeleton ----------------
  4.  
  5. use strict;
  6. use CGI qw(shortcuts font table td TR);
  7. use DBI;
  8.  
  9. # configuration bits
  10.  
  11. $MAIN::max_age   = 14;  # oldest record, in days, to display
  12. $MAIN::max_items = 50;  # maximum number of records to display
  13.  
  14. my $owner_name   = "Charlie Stross";
  15.  
  16. my $dbconf       = {
  17.                       "host"      => "localhost",
  18.                       "dbname"    => "guestbook",
  19.                       "username"  => "gb",
  20.                       "password"  => "gb_password",
  21.                       "table"     => "gb",
  22.                       "fields"    => [qw(comment_id author 
  23.                                          contents creation_time visible)],
  24.                  };
  25.  
  26. # end of configuration bits
  27.  
  28. my ($q) = new CGI;
  29.  
  30. my $connectstr = "DBI:mysql:database=" . 
  31.                  $dbconf->{dbname} .
  32.                  ";host=" . 
  33.                  $dbconf->{host} ;
  34.  
  35. my ($d) = DBI->connect($connectstr, 
  36.                        $dbconf->{username},
  37.                        $dbconf->{password}, 
  38.                        {'RaiseError' => 1});
  39.  
  40. print $q->header(-type => 'text/html',
  41.                  -status => '200 OK');
  42. print $q->start_html(-title => "$owner_name\'s guest book" ,
  43.                      -BGCOLOR => '#FFFFA0');
  44. print $q->h1("$owner_name\'s guest book");
  45. print $q->hr();
  46. print $q->start_blockquote();
  47. if ($q->param('data') == 1) {
  48.     insert_gb ($q, $dbconf, $d); 
  49.     print_gb  ($q, $dbconf, $d);
  50. } else {
  51.     print_gb  ($q, $dbconf, $d);
  52.     print_form($q);
  53. }
  54.  
  55. print $q->end_blockquote();
  56. print $q->hr();
  57. print $q->start_font({'size' => '-2'});
  58. print $q->p("This page generated for host ", $q->remote_host(), 
  59.             " (using ", $q->user_agent(), ") on ", scalar(localtime(time)));
  60. print $q->end_font();
  61.  
  62. print $q->end_html;
  63. $d->disconnect();
  64. exit 0;
  65.  
  66. #------------------- support routines ----------------------
  67.  
  68. sub print_form {
  69.     # print guestbook entry submission form. This includes a hidden
  70.     # field called 'data' that is set to '1', which tells the next
  71.     # invocation of the CGI program that it is processing a
  72.     # submission.
  73.  
  74.     my $q = shift; # CGI query object to use for building form
  75.  
  76.     print $q->startform; 
  77.     print $q->p("");
  78.     print $q->h2("Have your say");
  79.     print $q->hr(), "\n";
  80.     print $q->table( {"border" => "1",
  81.                       "bgcolor" => "#FFA0FF",
  82.                      },
  83.                      $q->hidden( -name => "data", -value => "1"),
  84.                      TR(
  85.                          td("From:"),
  86.                          td( $q->textfield("author"), 
  87.                              $q->i("Your name/email address goes here") )
  88.                        ),
  89.                      TR(
  90.                          td("Message:"),
  91.                          td( $q->textarea(-rows => "6", 
  92.                                           -cols => "60",
  93.                                           -wrap => "physical",
  94.                                           -name => "contents")
  95.                            )
  96.                        ),
  97.                      TR(
  98.                          td("Send comment:"),
  99.                          td( $q->submit(-name => "send") )
  100.                        )
  101.                    );
  102.     print $q->hr();
  103.     print $q->endform;
  104.     return;
  105. }
  106.  
  107. sub insert_gb {
  108.     # process a new guestbook submission. Strip anything suspicious
  109.     # (i.e. raw binaries) from the contents field, and insert into 
  110.     # database. 
  111.     my $cgi    = shift; # perl CGI object
  112.     my $dbconf = shift; # hash of configuration info
  113.     my $db     = shift; # perl DBI database handle
  114.  
  115.     # we want to sanitise the contents of 'author' and 'contents' here.
  116.     my $buffer = sanitise($cgi->param('contents'));
  117.     my $query  = "INSERT INTO " .  $dbconf->{table} . " " .
  118.                  "(author, contents, creation_time, visible, comment_id)\n" .
  119.                  "VALUES (" .
  120.                  $db->quote($cgi->param('author'))   . ", " .
  121.                  $buffer                 . ", "  .
  122.                  "CURRENT_TIMESTAMP()"   . ", "   .
  123.                  "1"                     . ", "   .
  124.                  "NULL"   .
  125.                  ")\n";
  126.    $db->do($query) or print "\n", $db->errstr(); 
  127.    return;
  128. }
  129.  
  130. sub print_gb {
  131.     # print guestbook contents We retrieve all
  132.     # records from the database that are not flagged with visible<>1,
  133.     # and which were submitted in the preceeding $MAIN::max_age
  134.     # days, and we order them in reverse order of date (to a maximum
  135.     # of $MAIN::max_items entries). 
  136.  
  137.     my $cgi    = shift; # CGI object
  138.     my $dbconf = shift; # hash of configuration info
  139.     my $db     = shift; # perl DBI database handle
  140.     my $count  = 0;     # count of retrieved rows from database
  141.  
  142.     print $cgi->h1("Things people said");
  143.  
  144.     print $cgi->start_table( {"border" => "1",
  145.                               "bgcolor" => "#FFA0FF"} );
  146.  
  147.     my $query = "SELECT comment_id, author, contents, " .
  148.                 "DATE_FORMAT(creation_time, '%W %M %Y') " .
  149.                 "FROM " .
  150.                 $dbconf->{table} . 
  151.                 " WHERE " .
  152.                 "visible=1 AND " .
  153.                 "(TO_DAYS(NOW()) - TO_DAYS(creation_time) <= $MAIN::max_age)" .
  154.                 " ORDER BY comment_id DESC\n";
  155.     
  156.     my $sth = $db->prepare($query);
  157.     $sth->execute();
  158.     while (my $ref = $sth->fetchrow_hashref() and 
  159.            $count <= $MAIN::max_items) {
  160.         $count++;
  161.         print $cgi->TR(
  162.                         td("From:"),
  163.                         td( $ref->{author}), 
  164.               ),
  165.               $cgi->TR(
  166.                         td("Date:"),
  167.                         td( $ref->{creation_time}),
  168.               ),
  169.               $cgi->TR(td("Comment:"),
  170.                        td(
  171.                            $cgi->pre(
  172.                              $ref->{contents}
  173.                            )
  174.                          )
  175.               );
  176.     }       
  177.     if ($count == 0) {
  178.         print $cgi->TR(
  179.                           td("Sorry, this guestbook is empty!")
  180.                       );
  181.     }
  182.     print $cgi->end_table;
  183.     print $cgi->hr();
  184.     return;
  185. }
  186.  
  187. sub sanitise {
  188.     # sanitise the contents of someone's posting. 
  189.     #
  190.     # A *really smart* guestbook would be smart enough to keep
  191.     # sane/legal HTML while ditching the dubious stuff. But this
  192.     # program is here to demonstrate MySQL and DBI, not whizzy CGI
  193.     # scripting.
  194.     #
  195.     # Currently all we do is replace carriage returns with <BR> tags, 
  196.     # and trust that the user will only enter ASCII text.  Feel free
  197.     # to extend this subroutine to do something more useful!
  198.     #
  199.  
  200.     my $buffer = shift;
  201.     $buffer =~ s/</</g;
  202.     $buffer =~ s/>/>/g;
  203.     $buffer = join("<BR>", grep(/^.+$/, split(/[\r\n]/, $buffer)));
  204.     $buffer    =~ s/'/\\'/g;
  205.     $buffer    = "'" . $buffer . "'";
  206.     return $buffer;
  207.  
  208. }
  209.